local resty_rsa = require "resty.rsa"
pub.debug = "off"

local PRIV_LEY = [[-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDM9UyYyG82+xHIA+Gtkayp0QElfhBe4ARvRngnyDc5+h8A2GLY
zemK+7PxDe3i2SQz0RT1opq2rYUlLBAZzRoVQxQ9bAjQaqswjAglM3qCHbLj85zp
oLKY/vsfB/2BAxhTjTsWmsnlPla2u49xOldLQBHvURMNijFyxT/RYxuY5wIDAQAB
AoGBAMzYejbVVPpxkwMChiMwzo5nOysaxQfeA/CnUN4J6NCEYUo5+wlPPBTRnrXV
QyYP+nPji3w5iUH9SW6ujGUNLfu3r842bQyKjf7tMOjkERG6DfJjIvGU4wIgfwC8
EWVZ5Skk15y57UBiRn3/p3ij/a05VmLR/Jj+xoo/DZuReE4xAkEA/u28nhroI/f9
4F9SSBs17iYpEUI3n6B7wIJOZhdi3Agzgni8+qf18a0ZCVUqBJOiO344mM4vrsBn
18m8qlS0yQJBAM3RzVMo3F536RVpciwrMkTh+RjGzhETtnLp2ts50y2Ffwy+3ZSi
YozkhXnFFuSyQmyJUSQCLcH+By5bGWlXKC8CQQC0bS6B+Ck0y+AzXUOvJRMWaovG
W0djAwKTTaaPOx4M/QD35txZy2aWlhySLmR+uL6pvLvx6nx1Alh8sZuGMk2BAkAm
UguykgcFp7nD/M//HUPMw24HiOxRDaSInLXc31VMQnC3RMoopFtI9DtNwr5SckYf
wylSVP2EAvH/VYLTtCCNAkAENc175hs0EvukSyunQLFl/AhuRDo3QoGddLseMd0N
5WN01xjhCgLXNUqMQIyAIBAr59W4QbawNFyzqcDR3UvM
-----END RSA PRIVATE KEY-----]]

local PUBLIC_KEY  = [[-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDM9UyYyG82+xHIA+Gtkayp0QEl
fhBe4ARvRngnyDc5+h8A2GLYzemK+7PxDe3i2SQz0RT1opq2rYUlLBAZzRoVQxQ9
bAjQaqswjAglM3qCHbLj85zpoLKY/vsfB/2BAxhTjTsWmsnlPla2u49xOldLQBHv
URMNijFyxT/RYxuY5wIDAQAB
-----END PUBLIC KEY-----]]

--rsa加密
function pub.rsa_encrypt(msg)
    local strarr={}
	local b64str={}
	local allStr=""
	local pub, err = resty_rsa:new({ public_key = PUBLIC_KEY })
	if not pub then
        return
    end
    
	local msgLen  = #msg
	if msgLen <= 117 then
		--正常加密
		return ngx.encode_base64(pub:encrypt(msg))
	else
		--分段加密
		local arrLen = math.ceil(msgLen/117)
		for i=1,arrLen,1 do
			strarr[i]=string.sub(msg, ((i-1)*117)+1, 117*i)
			b64str[i]=ngx.encode_base64(pub:encrypt(strarr[i]))
			--去掉第172个=字符
			b64str[i] = string.sub(b64str[i], 1, -2)
			--拼接base64字符串
			allStr=allStr..b64str[i]
		end
		return allStr
	end
    
end

--ras解密
function pub.rsa_decrypt(msg)
	local priv, err = resty_rsa:new({ private_key = PRIV_LEY })
    if not priv then
        return
    end
    local b64len = #msg
    
    if b64len > 172 then
        --分段解密
        local arrlen = (b64len)/171
        local b64arr = {}
        local dearr = {}
        local allStr = ""

        for i=1,arrlen,1 do
            b64arr[i] = string.sub(msg,((i-1)*171)+1,171*i)
            dearr[i] = pub.rsa_decrypt(b64arr[i]..'=')
        end
        --合并字符串
        for i=1,arrlen,1 do
            allStr = allStr..dearr[i]
        end
        return allStr
    else
        --正常解密
        return priv:decrypt(ngx.decode_base64(msg))
    end
end